package com.das.mechanic_base.mvp.view.camera;

import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.adapter.camera.X3CropPreviewAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3BasePresenter;
import com.das.mechanic_base.bean.alone.CameraCropBean;
import com.das.mechanic_base.bean.camera.CameraBean;
import com.das.mechanic_base.bean.camera.TagLocation;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.das.mechanic_base.widget.X3BottomSelectTagDialog;
import com.das.mechanic_base.widget.X3PictureNewTagLayout;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import razerdp.basepopup.BasePopupWindow;

public class X3CameraCropActivity extends X3BaseActivity implements X3CropPreviewAdapter.IOnCameraPreview, X3BottomSelectTagDialog.IOnSelectTag {

    @BindView(R2.id.rlv_camera)
    RecyclerView rlv_camera;
    @BindView(R2.id.btn_ok)
    Button btn_ok;
    @BindView(R2.id.iv_image)
    ImageView iv_image;
    @BindView(R2.id.pl_tag)
    X3PictureNewTagLayout pl_tag;
    @BindView(R2.id.tv_tag)
    TextView tv_tag;
    @BindView(R2.id.tv_rota)
    TextView tv_rota;
    @BindView(R2.id.rl_parent)
    RelativeLayout rl_parent;
    @BindView(R2.id.ll_bottom)
    LinearLayout ll_bottom;
    @BindView(R2.id.iv_last)
    ImageView iv_last;
    @BindView(R2.id.tv_tailor)
    TextView tv_tailor;

    private List<String> cameraList;

    private X3CropPreviewAdapter previewAdapter;

    /**
     * 存储图片标签信息
     */
    private HashMap<Integer,Multimap<String, TagLocation>> tagMap;

    private List<Integer> rotaList;

    private boolean isTouch;
    private int currentIndex = 0;
    private List<String> newList;
    private int showIndex;
    private int[] viewLocation;
    private int imgHeight;
    private boolean isLoad;
    private X3BottomSelectTagDialog tagDialog;
    private long itemId;
    private boolean isSubmit;
    private boolean isWork;

    @Override
    protected int getLayoutId() {
        EventBus.getDefault().register(this);
        return R.layout.x3_activity_camera_crop;
    }

    @Override
    protected void initView() {
        rl_parent.setPadding(0, X3StatusBarUtil.getStatusBarHeight(this),0,0);

        itemId = getIntent().getLongExtra("itemId", 0L);

        isWork = getIntent().getBooleanExtra("isWork", false);

        viewLocation = new int[2];

        iv_image.getLocationOnScreen(viewLocation);

        cameraList = (List<String>) getIntent().getSerializableExtra("cameraList");

        if (X3StringUtils.isListEmpty(cameraList)) {
            finish();
        }

        tagMap = new HashMap<>();

        rotaList = new ArrayList<>();

        for (int i = 0; i < cameraList.size(); i++) {
            tagMap.put(i, ArrayListMultimap.create());
            rotaList.add(0);
        }

        imgHeight = getIntent().getIntExtra("imgHeight", 0);

        if (imgHeight != 0) {
            ViewGroup.LayoutParams layoutParams = iv_image.getLayoutParams();
            layoutParams.height = imgHeight;
            iv_image.setLayoutParams(layoutParams);
        }

        iv_image.post(() -> {
            pl_tag.addMaxHeight(iv_image.getHeight());
        });

        Glide.with(this).load(cameraList.get(0)).into(iv_image);

        btn_ok.setText(getString(R.string.x3_camera_crop_ok) + "(" + cameraList.size() + ")");

        rlv_camera.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));

        previewAdapter = new X3CropPreviewAdapter(this);

        rlv_camera.setAdapter(previewAdapter);

        previewAdapter.changeCameraList(cameraList);

        previewAdapter.setiOnCameraPreview(this);

        pl_tag.setOnTouchLayoutListence(new X3PictureNewTagLayout.OnTouchLayoutListence() {
            @Override
            public void OnTouchListener() {
                if (!X3Utils.isFastClick()) {
                    return;
                }
                isTouch = true;
                if (tagDialog == null) {
                    tagDialog = new X3BottomSelectTagDialog(X3CameraCropActivity.this);
                    tagDialog.setiOnSelectTag(X3CameraCropActivity.this);
                }
                tagDialog.setAdjustInputMethod(true)
                        .setBackPressEnable(true)
                        .setAutoShowInputMethod(tagDialog.findViewById(R.id.ed_input), true)
                        .setAdjustInputMode(R.id.ed_input, BasePopupWindow.FLAG_KEYBOARD_ALIGN_TO_ROOT | BasePopupWindow.FLAG_KEYBOARD_ANIMATE_ALIGN)
                        .showPopupWindow();
                tagDialog.setTagDetectionId(itemId);
            }

            @Override
            public void OnShowBottomView(boolean isShow) {
                ll_bottom.setVisibility(isShow ? View.VISIBLE : View.GONE);
            }

            @Override
            public void OnChangeTagLocation() {
                Multimap<String, TagLocation> stringTagLocationMultimap = tagMap.get(currentIndex);
                Multimap<String, TagLocation> tagLocation = pl_tag.getTagLocation();
                stringTagLocationMultimap.clear();
                if (tagLocation != null && tagLocation.size() > 0) {
                    stringTagLocationMultimap.putAll(tagLocation);
                }
                tagMap.put(currentIndex,stringTagLocationMultimap);
            }
        });
    }

    @Override
    protected X3BasePresenter createPresenter() {
        return null;
    }

    @OnClick({R2.id.iv_last,R2.id.tv_tag,R2.id.tv_rota,R2.id.rl_bottom,R2.id.tv_tailor,R2.id.btn_ok})
    public void onViewClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_last) {
            finish();
        } else if (id == R.id.tv_tailor) {
            XXPermissions.with(this)
                    .permission(Permission.Group.STORAGE)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if (all) {
                                ActivityOptionsCompat options =
                                        ActivityOptionsCompat.makeSceneTransitionAnimation(X3CameraCropActivity.this,
                                                iv_image, ViewCompat.getTransitionName(iv_image));
                                Intent intent = new Intent(X3CameraCropActivity.this, X3CropActivity.class);
                                intent.putExtra("imgHeight", imgHeight);
                                intent.putExtra("cropPath", cameraList.get(currentIndex));
                                intent.putExtra("cropRota", rotaList.get(currentIndex));
                                ActivityCompat.startActivityForResult(X3CameraCropActivity.this, intent, X3Constent.REQUEST_CODE_PREVIEW, options.toBundle());
                            } else {
                                XXPermissions.startPermissionActivity(X3CameraCropActivity.this, permissions);
                            }
                        }

                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            XXPermissions.startPermissionActivity(X3CameraCropActivity.this, permissions);
                        }
                    });
        } else if (id == R.id.tv_tag) {
            if (!X3Utils.isFastClick()) {
                return;
            }
            isTouch = false;
            if (tagDialog == null) {
                tagDialog = new X3BottomSelectTagDialog(X3CameraCropActivity.this);
                tagDialog.setiOnSelectTag(X3CameraCropActivity.this);
            }
            tagDialog.setAdjustInputMethod(true)
                    .setBackPressEnable(true)
                    .setAutoShowInputMethod(tagDialog.findViewById(R.id.ed_input), false)
                    .setAdjustInputMode(R.id.ed_input, BasePopupWindow.FLAG_KEYBOARD_ALIGN_TO_ROOT | BasePopupWindow.FLAG_KEYBOARD_ANIMATE_ALIGN)
                    .showPopupWindow();
            tagDialog.setTagDetectionId(itemId);
        } else if (id == R.id.tv_rota) {
            Integer rota = rotaList.get(currentIndex);
            rota += 90;
            rotaList.remove(currentIndex);
            rotaList.add(currentIndex, rota);
            iv_image.animate().rotation(rota).setDuration(300).start();
        } else if (id == R.id.rl_bottom) {// 阻止添加标签的view的触摸和点击事件
        } else if (id == R.id.btn_ok) {
            if (!X3Utils.isFastClick() || isSubmit) {
                return;
            }
            callBackTagToAlone();

            isSubmit = true;
            /**
             * 生成图片
             */
            if (previewAdapter != null) {
                previewAdapter.changeNoDelete();
            }
            showLoading("");
            newList = new ArrayList<>();
            iv_last.setVisibility(View.GONE);

            // 生成图片 回传
            compressImage(0);
        }
    }

    /**
     * 将标签传回去
     */
    private void callBackTagToAlone() {
        if (tagMap == null) {
            return;
        }
        HashMap<String,Integer> tagNumMap = new HashMap<>();
        for (int key : tagMap.keySet()) {
            Multimap<String, TagLocation> tagMultimap = tagMap.get(key);
            if (tagMultimap == null) {
                continue;
            }
            Multiset<String> keys = tagMultimap.keys();
            for (String tag : keys.elementSet()) {
                Object[] tagLocations = tagMultimap.get(tag).toArray();
                if (tagLocations == null) {
                    continue;
                }
                if (tagNumMap.containsKey(tag)) {
                    tagNumMap.put(tag,tagNumMap.get(tag) + tagLocations.length);
                }else {
                    tagNumMap.put(tag,tagLocations.length);
                }
            }
        }
        CameraBean cameraBean = new CameraBean(X3Constent.CODE_ALONE_IMAGE_TO_QUESTION, tagNumMap);
        cameraBean.isWork = isWork;
        EventBus.getDefault().post(cameraBean);
    }

    private void compressImage(int showIndex) {
        this.showIndex = showIndex;
        showIndexImage(showIndex);

        iv_image.postDelayed(() -> {

            View screenView = getWindow().getDecorView();
            screenView.setDrawingCacheEnabled(true);
            screenView.buildDrawingCache();

            Bitmap bitmap = screenView.getDrawingCache();
            if (bitmap == null) {
                iv_last.setVisibility(View.VISIBLE);

            }else {
                if (iv_image != null) {
                    int outWidth = iv_image.getWidth();
                    int outHeight = iv_image.getHeight();
                    if (outWidth > bitmap.getWidth()) {
                        outWidth = bitmap.getWidth();
                    }
                    if (outHeight > bitmap.getHeight()) {
                        outHeight = bitmap.getHeight();
                    }

                    //从屏幕整张图片中截取指定区域
                    int rota = rotaList.get(showIndex);
                    if (rota / 90 % 2 == 0) {
                        bitmap = Bitmap.createBitmap(bitmap, 0, viewLocation[1] + X3StatusBarUtil.getStatusBarHeight(X3CameraCropActivity.this), outWidth, outHeight);
                    }else {
                        bitmap = Bitmap.createBitmap(bitmap, 0, viewLocation[1] + X3StatusBarUtil.getStatusBarHeight(X3CameraCropActivity.this), outWidth, outWidth);
                    }

                    screenView.setDrawingCacheEnabled(false);
                    X3FileUtils.saveFileBitmapCompress(this,bitmap, path -> {
                        newList.add(path);
                        Log.e("up_load_","newList.add(path) =" + path);

                        if (newList.size() == cameraList.size()) {
                            compressSuccess();
                        }else {
                            compressImage(newList.size());
                        }
                    });
                }
            }
        },500);
    }

    /**
     * 生成图片成功 回传
     */
    private void compressSuccess() {
        /**
         * 回传图片
         */
        isSubmit = false;
        iv_last.setVisibility(View.VISIBLE);
        CameraBean cameraBean = new CameraBean(X3Constent.CODE_CAMERA_REQUEST, newList);
        cameraBean.isWork = isWork;
        EventBus.getDefault().post(cameraBean);
        finish();
    }

    @Override
    public boolean isTransparent() {
        return false;
    }

    @Override
    public void iOnCameraPreview(String path, boolean isPreview,int lastIndex,int currentIndex) {
        this.currentIndex = currentIndex;
        /**
         * 展示对应下标的图片以及标签
         */
        showIndexImage(currentIndex);

    }

    private void showIndexImage(int currentIndex) {

        /**
         * 获取当前的标签数据
         */
        pl_tag.removeViews();
        Multimap<String, TagLocation> locationHashMap = tagMap.get(currentIndex);
        pl_tag.showTagLocation(locationHashMap);

        iv_image.setRotation(rotaList.get(currentIndex));

        Glide.with(this).load(cameraList.get(currentIndex)).into(iv_image);
    }

    @Override
    public void iOnCameraDelete(String path) {

        if (X3StringUtils.isEmpty(path)) {
            return;
        }
        if (X3StringUtils.isListEmpty(cameraList)) {
            return;
        }
        if (!cameraList.contains(path)) {
            return;
        }
        tagMap.remove(cameraList.indexOf(path));
        cameraList.remove(path);

        btn_ok.setText(getString(R.string.x3_camera_crop_ok) + "(" + cameraList.size() + ")");

        CameraCropBean cropBean = new CameraCropBean();
        cropBean.type = 1;
        cropBean.cameraList = cameraList;
        EventBus.getDefault().post(cropBean);

        if (X3StringUtils.isListEmpty(cameraList)) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetTag(CameraCropBean cropBean) {
        // 传递下方更新标签
        int type = (int) cropBean.type;
        switch (type) {
            case 0:
                addTag(cropBean.tag);
                break;
            case 2:
                if (X3StringUtils.isListEmpty(cameraList)) {
                    return;
                }
                if (cameraList.contains(cropBean.beforePath)) {
                    int i = cameraList.indexOf(cropBean.beforePath);
                    cameraList.remove(i);
                    cameraList.add(i,cropBean.path);

                    Glide.with(this).load(cameraList.get(0)).into(iv_image);
                    if (previewAdapter != null) {
                        previewAdapter.changeCameraList(cameraList,i);
                    }
                }
                break;
        }
    }

    /**
     * 添加标签
     * @param content
     */
    protected void addTag(String content) {
        pl_tag.addData(content, !isTouch,0,1.0f,true);

        /**
         * 存储上一个图片的所有标签数据
         */
        Multimap<String, TagLocation> stringTagLocationMultimap = tagMap.get(currentIndex);
        Multimap<String, TagLocation> tagLocation = pl_tag.getTagLocation();
        if (stringTagLocationMultimap == null) {
            stringTagLocationMultimap = ArrayListMultimap.create();
        }else {
            stringTagLocationMultimap.clear();
        }
        if (tagLocation != null && tagLocation.size() > 0) {
            stringTagLocationMultimap.putAll(tagLocation);
        }
        tagMap.put(currentIndex,stringTagLocationMultimap);
    }

    @Override
    protected void onDestroy() {
        hideLoading();
        EventBus.getDefault().unregister(this);
        if (iv_image.getAnimation() != null) {
            iv_image.getAnimation().cancel();
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("图片预览页");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("图片预览页");
    }

    @Override
    public void iOnSelectTag(String content) {
        addTag(content);
    }
}